#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import logging
import time
import datetime
import os
import oauth
import sys
import simplejson
import random
from init import *

class mixiGraph(webapp.RequestHandler):
    def get(self):
        c = consumer_keys("./lib/data/key.json")
        CONSUMER_KEY = c["mixi"]["consumer_key"]
        CONSUMER_SECRET_KEY = c["mixi"]["consumer_secret_key"]

        scope = 'r_profile r_voice w_voice'
        OAUTH2_URL = 'https://mixi.jp/connect_authorize.pl?client_id=%s&response_type=code&display=pc&scope=%s' % (CONSUMER_KEY,scope)
        """#client = oauth.mixiGraphClient(CONSUMER_KEY, CONSUMER_SECRET_KEY, callback_url)
        #print client"""
        cookies = self.request.cookies
        token = cookies.get('access_token',"")
        refresh_token = cookies.get('refresh_token',"")
        token_flag = 0
        pofileApi = 'http://api.mixi-platform.com/2/people/@me/@self?oauth_token=%s' % token
        vApiR = 'http://api.mixi-platform.com/2/voice/statuses/@me/user_timeline?oauth_token=%s' % token
        #print token
        json={}
        jsons = ""
        tv = {}
        if token != "" :
            token_flag = 1
            f=""
            v=""
            rpc = urlfetch.create_rpc()
            urlfetch.make_fetch_call(rpc, vApiR)
            try:
                v = rpc.get_result() 
            except urlfetch.DownloadError:
                print ""
            
            p = memcache.get("json")
            f = urlfetch.fetch(pofileApi)
            # v = urlfetch.fetch(vApiR)
            if(f.status_code==200):
                token_flag = 1
                jsons = f.content;
                json=simplejson.loads(f.content)
                memcache.set("json",json);
                jsonv=simplejson.loads(v.content)
                tv["profile"] = json
                tv["voices"] = v.content
                tv["voice"] = jsonv
                tv["jsons"] = jsons
                tv["refresh_token"] = refresh_token
                tv["consumer_key"] = CONSUMER_KEY
                tv["consumer_secret_key"] = CONSUMER_SECRET_KEY
            else:
                if refresh_token != "" :
                    r = 'http://localhost:9999/refresh?refresh_token=%s' % (refresh_token)
                    #f = urlfetch.fetch(url=r,method=urlfetch.GET, deadline=10)
                    rpc = urlfetch.create_rpc()
                    urlfetch.make_fetch_call(rpc, r)
                    try:
                        f = rpc.get_result()
                    except urlfetch.DownloadError:
                        self.redirect(OAUTH2_URL)
                    if(f.status_code==200):
                        t = simplejson.loads(f.content)
                        token = t["access_token"]
                        pofileApi = 'http://api.mixi-platform.com/2/people/@me/@self?oauth_token=%s' % token
                        p = urlfetch.fetch(pofileApi)
                        if(p.status_code==200):
                            token_flag = 1
                            jsons = p.content
                            json=simplejson.loads(jsons)
                            tv["profile"] = json
                            tv["jsons"] = jsons
                            
                    else:
                        token_flag = 0
                        
        tv["oauthUrl"]=OAUTH2_URL
        tv["login"]=token_flag
        tmpl_path = os.path.dirname(__file__)+"/tmpl/"
        path = os.path.join(tmpl_path, 'index.tmp')
        self.response.out.write(template.render(path, tv))
            
application = webapp.WSGIApplication([('/', mixiGraph)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
